﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using TierApplication;
using System.Data;
using DevExpress.Web.ASPxEditors;

public partial class System_Product_Product : BasePage
{
    #region private
    T_PRODUCT mProduct = new T_PRODUCT();
    string ProductImageFolder = "..\\..\\ProductImages\\";
    private const string inputQueryStringIDKey = "ProductID";
    private const string inputQueryStringPageModeKey = "pagemode";
    private const string currentPageModeKey = "CurrentPageMode";
    private const string mDataModel = "mDataModel";

    public enum PageMode
    {
        add,
        update,
        query,
        select
    }
    private Nullable<PageMode> pm;



    #endregion



    protected void Page_Load(object sender, EventArgs e)
    {       
        if (Page.IsPostBack)
        {
            pm = ViewState[currentPageModeKey] as Nullable<PageMode>;
        }
        else
        {
            #region 权限检查
            //if (!Context.User.Identity.IsAuthenticated)
            //{
            //    return;
            //}
            #endregion

            BindBandwidth();
            BindLifeTime();
            BindSchool();
            BindCategoryId();

            this.txtProductId.Text = Page.Request.QueryString[inputQueryStringIDKey];
            this.pagemode.Value = Page.Request.QueryString[inputQueryStringPageModeKey];

            switch (this.pagemode.Value.ToLower().Trim())
            {
                case "add":
                    pm = PageMode.add;
                    break;
                case "update":
                    pm = PageMode.update;
                    break;
                case "query":
                    pm = PageMode.query;
                    break;
                case "select":
                    pm = PageMode.select;
                    break;
                default:
                    pm = PageMode.add;
                    break;
            }
            ViewState[currentPageModeKey] = pm;

            if (!string.IsNullOrEmpty(this.txtProductId.Text.Trim()))
            {
                LoadProduct(this.txtProductId.Text.Trim());
            }
        }

    }

    private void LoadProduct(String ProductID)
    {
        ListEditItem theselected;
        T_PRODUCT mProduct = new T_PRODUCT();
        mProduct.GetModel(ProductID);
        ViewState[mDataModel] = mProduct;

        txtPRODUCTNAME.Text = mProduct.PRODUCTNAME;

        if (!String.IsNullOrEmpty(mProduct.SCHOOLID))
        {
            theselected = ddlSCHOOLID.Items.FindByValue(mProduct.SCHOOLID);
            if (theselected != null)
            {
                ddlSCHOOLID.SelectedItem = theselected;
            }
        }

        if (!String.IsNullOrEmpty(mProduct.BANDWIDTH))
        {
            theselected = ddlBANDWIDTH.Items.FindByValue(mProduct.BANDWIDTH);
            if (theselected != null)
            {
                ddlBANDWIDTH.SelectedItem = theselected;
            }
        }

        if (!String.IsNullOrEmpty(mProduct.LIFETIME))
        {
            theselected = ddlLIFETIME.Items.FindByValue(mProduct.LIFETIME);
            if (theselected != null)
            {
                ddlLIFETIME.SelectedItem = theselected;
            }
        }

        if (!String.IsNullOrEmpty(mProduct.CATEGORYID))
        {
            theselected = ddlCATEGORYID.Items.FindByValue(mProduct.CATEGORYID);
            if (theselected != null)
            {
                ddlCATEGORYID.SelectedItem = theselected;
            }
        }

        this.txtPURCHASEPRICE.Text = mProduct.PURCHASEPRICE.ToString();
        this.txtMARKETPRICE.Text = mProduct.MARKETPRICE.ToString();
        this.txtDISCOUNT.Text = mProduct.DISCOUNT.ToString();
        this.txtDISCOUNTPRICE.Text = mProduct.DISCOUNTPRICE.ToString();
        this.txtUNITPRICE.Text = mProduct.UNITPRICE.ToString();
        //this.txtPRODUCTIMAGE.Text = mProduct.PRODUCTIMAGE;
        this.ProductImage.Src = ProductImageFolder + mProduct.PRODUCTIMAGE;
        this.bigImg.HRef = ProductImageFolder + mProduct.PRODUCTIMAGE;
        this.ProductImage.Width = 100;
        this.ProductImage.Height = 100;

        if (!String.IsNullOrEmpty(mProduct.CATEGORYID))
        {
            theselected = ddlCATEGORYID.Items.FindByValue(mProduct.CATEGORYID);
            if (theselected != null)
            {
                ddlCATEGORYID.SelectedItem = theselected;
            }
        }

        this.txtDESCN.Text = mProduct.DESCN;
        this.txtREMARK.Text = mProduct.REMARK;
        this.txtREMARK1.Text = mProduct.REMARK1;
        this.txtREMARK2.Text = mProduct.REMARK2;
        //this.txtCREATEDATE.Text = model.CREATEDATE.ToString();
        //this.txtLASTALTERUSERID.Text = model.LASTALTERUSERID;
        //this.txtLASTALTERTIME.Text = model.LASTALTERTIME.ToString();

    }

    private void BindBandwidth()
    {
        DataSet ds = P_DDCODE.GetListByType(P_DDCODE.DDType.Bandwidth.ToString());
        this.ddlBANDWIDTH.DataSource = ds.Tables[0].DefaultView;
        this.ddlBANDWIDTH.TextField = "CodeName";
        this.ddlBANDWIDTH.ValueField = "CodeID";
        this.ddlBANDWIDTH.DataBind();
    }

    private void BindLifeTime()
    {
        DataSet ds = P_DDCODE.GetListByType(P_DDCODE.DDType.LifeTime.ToString());
        this.ddlLIFETIME.DataSource = ds.Tables[0].DefaultView;
        this.ddlLIFETIME.TextField = "CodeName";
        this.ddlLIFETIME.ValueField = "CodeID";
        this.ddlLIFETIME.DataBind();
    }

    private void BindCategoryId()
    {
        DataSet ds = P_DDCODE.GetListByType(P_DDCODE.DDType.CategoryId.ToString());
        this.ddlCATEGORYID.DataSource = ds.Tables[0].DefaultView;
        this.ddlCATEGORYID.TextField = "CodeName";
        this.ddlCATEGORYID.ValueField = "CodeID";
        this.ddlCATEGORYID.DataBind();
    }
    
    private void BindSchool()
    {
        T_SCHOOL mSchool = new T_SCHOOL();
        DataSet ds = mSchool.GetList("");
        this.ddlSCHOOLID.DataSource = ds;
        this.ddlSCHOOLID.ValueField = "SCHOOLID";
        this.ddlSCHOOLID.TextField = "SCHOOLNAME";
        this.ddlSCHOOLID.DataBind();
        this.ddlSCHOOLID.Items.Insert(0, new ListEditItem("(全部)", ""));
    }

    protected void btnProductSave_CallBack(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
        mProduct.PRODUCTNAME = this.txtPRODUCTNAME.Text;
        mProduct.SCHOOLID = (string)this.ddlSCHOOLID.SelectedItem.Value;
        mProduct.BANDWIDTH = (string)this.ddlBANDWIDTH.SelectedItem.Value;
        mProduct.LIFETIME = (string)this.ddlLIFETIME.SelectedItem.Value;
        mProduct.PURCHASEPRICE = decimal.Parse(this.txtPURCHASEPRICE.Text);
        mProduct.MARKETPRICE = decimal.Parse(this.txtMARKETPRICE.Text);
        mProduct.DISCOUNT = decimal.Parse(this.txtDISCOUNT.Text);
        mProduct.DISCOUNTPRICE = decimal.Parse(this.txtDISCOUNTPRICE.Text);
        mProduct.UNITPRICE = decimal.Parse(this.txtUNITPRICE.Text);
        //mProduct.PRODUCTIMAGE = this.txtPRODUCTIMAGE.Text;
        mProduct.CATEGORYID = this.ddlCATEGORYID.Text;
        mProduct.DESCN = Server.HtmlDecode(this.txtDESCN.Text);
        mProduct.REMARK = this.txtREMARK.Text;
        mProduct.REMARK1 = this.txtREMARK1.Text;
        mProduct.REMARK2 = this.txtREMARK2.Text;
        DateTime CREATEDATE = DateTime.Now;
        //UserInfo mUserInfo = (UserInfo)Session["UserInfo"];
      
        mProduct.LASTALTERUSERID = base.CurrentUserCode;
        DateTime LASTALTERTIME = DateTime.Now;

        if (UpLoadImg())
            return ;

        string sProductID = e.Parameter;
        if (String.IsNullOrEmpty(sProductID))
        {
            mProduct.PRODUCTID = TranUtils.GetProductID();
            txtProductId.Text = mProduct.PRODUCTID;
            mProduct.Add();
        }
        else
        {
            mProduct.PRODUCTID = this.txtProductId.Text;
            mProduct.Update();
        }

        e.Result = mProduct.PRODUCTID;

    }

    protected void btnProductSave_Click(object sender, EventArgs e)
    {
        string sProductID = this.txtProductId.Text;
        if (String.IsNullOrEmpty(sProductID))
        {
            DateTime CREATEDATE = DateTime.Now;
            mProduct.CREATEDATE = CREATEDATE;
        }
        else
        {
            mProduct = ViewState[mDataModel] as T_PRODUCT;
        }

        mProduct.PRODUCTNAME = this.txtPRODUCTNAME.Text;
        mProduct.SCHOOLID = (string)this.ddlSCHOOLID.SelectedItem.Value;
        mProduct.BANDWIDTH = (string)this.ddlBANDWIDTH.SelectedItem.Value;
        mProduct.LIFETIME = (string)this.ddlLIFETIME.SelectedItem.Value;
        mProduct.PURCHASEPRICE = decimal.Parse(this.txtPURCHASEPRICE.Text);
        mProduct.MARKETPRICE = decimal.Parse(this.txtMARKETPRICE.Text);
        mProduct.DISCOUNT = decimal.Parse(this.txtDISCOUNT.Text);
        mProduct.DISCOUNTPRICE = decimal.Parse(this.txtDISCOUNTPRICE.Text);
        mProduct.UNITPRICE = decimal.Parse(this.txtUNITPRICE.Text);
        mProduct.CATEGORYID = (string)this.ddlCATEGORYID.SelectedItem.Value;
        mProduct.DESCN = Server.HtmlDecode(this.txtDESCN.Text);
        mProduct.REMARK = this.txtREMARK.Text;
        mProduct.REMARK1 = this.txtREMARK1.Text;
        mProduct.REMARK2 = this.txtREMARK2.Text;
        mProduct.LASTALTERUSERID = "";
        DateTime LASTALTERTIME = DateTime.Now;
        mProduct.LASTALTERTIME = LASTALTERTIME;

        bool uploadfile = UpLoadImg();
        if (!uploadfile)
        {
            return ;
        }

        if (String.IsNullOrEmpty(sProductID))
        {
            mProduct.PRODUCTID = TranUtils.GetProductID();
            txtProductId.Text = mProduct.PRODUCTID;
            mProduct.Add();
        }
        else
        {
            mProduct.PRODUCTID = this.txtProductId.Text;
            mProduct.Update();
        }
        this.ClientScript.RegisterStartupScript(this.GetType(),"", "<script language='javascript'>window.returnValue='ok';window.opener=null; window.close();</script>");

    }


    #region 上传图片文件
    private bool UpLoadImg()
    {
        if (this.txtFileUp.PostedFile != null)
        {
            string strErr = "";
            int size1 = this.txtFileUp.PostedFile.ContentLength;//大小
            if (size1 > 1)
            {
                if (size1 > 1024000)
                {
                    strErr += "保存失败：文件大小不能大于1M！\\n";
                }

                if (strErr != "")
                {
                    TierService.MessageBox.Show(this, strErr);
                    return false;
                }

                string UploadFileType = this.txtFileUp.PostedFile.ContentType;
                string UploadFilePath = this.txtFileUp.PostedFile.FileName;
                int start = UploadFilePath.LastIndexOf("\\");

                string filename = UploadFilePath.Substring(start + 1);
                filename = DateTime.Now.ToString("yyyyMMddHHmmss") + filename;

                mProduct.PRODUCTIMAGE = filename;

                Stream StreamObject = this.txtFileUp.PostedFile.InputStream;//建立数据流对像
                switch (UploadFileType)
                {
                    case "image/png":
                    case "image/x-png":
                    case "image/gif":
                    case "image/bmp":
                    case "image/pjpeg":
                        {
                            System.Drawing.Image myImage = System.Drawing.Image.FromStream(StreamObject);
                            int w = myImage.Width;
                            int h = myImage.Height;
                        }
                        break;
                    case "application/x-shockwave-flash":
                        break;
                    case "video/x-ms-wmv":
                    case "video/mpeg":
                    case "video/x-ms-asf":
                    case "video/avi":
                    case "audio/mpeg":
                    case "audio/mid":
                    case "audio/wav":
                    case "audio/x-ms-wma":
                        break;
                    default:
                        strErr += "保存失败：不允许该文件格式上传！\\n";
                        break;
                }

                if (strErr != "")
                {
                    TierService.MessageBox.Show(this, strErr);
                    return false;
                }

                string path = ProductImageFolder + filename;
                path = Server.MapPath(path);
                try
                {
                    this.txtFileUp.PostedFile.SaveAs(path); //如果抱错，注意UploadFile目录的访问权限
                }
                catch //(System.Exception ex)
                {
                    //Response.Write("请确保" + ProductImageFolder + "目录具有写的权限。");
                    TierService.MessageBox.Show(this, "保存失败：请确保" + ProductImageFolder + "目录具有写的权限。");
                    return false;
                }
            }
        }
        return true;
    }
    #endregion
}